package com.permission.systempermission.config;

import com.sun.xml.internal.ws.api.server.SDDocument;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.service.*;
import static java.util.Collections.singletonList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(Environment environment) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true) //1、通过enable()方法配置是否启用swagger，如果是false，swagger将不能在浏览器中访问了
                .select()   //通过.select()方法，去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .apis(RequestHandlerSelectors.basePackage("com.permission.systempermission.controller"))
                .build()
                .securityContexts(Arrays.asList(securityContext())) //配置token认证
                // ApiKey的name需与SecurityReference的reference保持一致
                .securitySchemes(Arrays.asList(new ApiKey("token", "token",  "header")));
    }

    public ApiInfo apiInfo() {
        Contact contact = new Contact("", "", "");
        return new ApiInfo("springboot+mysql+redis+securty的权限系统",  //标题
                "权限后台系统接口", //描述
                "1.0.0", //版本
                "", // 组织链接
                contact, //联系人信息
                "", //许可
                "",
                new ArrayList<>() //扩展
        );
    }



    //配置token认证
    //https://blog.csdn.net/u022812849/article/details/117374768
    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any()) // 对所有路径生效
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope
                = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return singletonList(
                new SecurityReference("token", authorizationScopes));
    }

}
